//
//  ExpressSendingTableViewController.m
//  Express
//
//  Created by lanou on 16/1/8.
//  Copyright © 2016年 FJY. All rights reserved.
//

#import "ExpressSendingTableViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "BaseHeader.h"

@interface ExpressSendingTableViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *manager;
@property (nonatomic, assign) CLLocationCoordinate2D currentCoordinate;
@property (nonatomic, strong) NSMutableArray *nearbyInfoArray;

@end

@implementation ExpressSendingTableViewController

- (NSMutableArray *)nearbyInfoArray {
    if (!_nearbyInfoArray) {
        _nearbyInfoArray = [[NSMutableArray alloc] init];
    }
    return _nearbyInfoArray;
}

- (void)viewWillAppear:(BOOL)animated {
    [self locate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
    
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(localCity)];
    
}

- (void)localCity {
    
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.currentCoordinate = self.currentCoordinate;
    mapVC.nearbyInfoArray = self.nearbyInfoArray;
    [self.navigationController pushViewController:mapVC animated:YES];
}

- (void)locate {
    if ([CLLocationManager locationServicesEnabled]) {
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
        _manager.distanceFilter = 10.0;
        if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
            [_manager requestWhenInUseAuthorization];
        }
        [_manager startUpdatingLocation];
    }
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *currentLocation = [locations lastObject];
    self.currentCoordinate = currentLocation.coordinate;
    NSLog(@"%f %f",self.currentCoordinate.longitude , self.currentCoordinate.latitude);

//    CLGeocoder *gecoder = [[CLGeocoder alloc] init];
//    [gecoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        if (!error) {
//            CLPlacemark *placeMark = [placemarks lastObject];
            [self fetchNearbyInfo];
//        }
//        [_manager stopUpdatingLocation];
//    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@",error);
}

- (void)fetchNearbyInfo {
    CLLocationDegrees latitude = self.currentCoordinate.latitude;
    CLLocationDegrees longitude = self.currentCoordinate.longitude;
    CLLocationCoordinate2D location=CLLocationCoordinate2DMake(latitude, longitude);
    
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 500, 500);
    
    MKLocalSearchRequest *requst = [[MKLocalSearchRequest alloc] init];
    requst.region = region;
    requst.naturalLanguageQuery = @"快递";
    MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:requst];
    
    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
        if (!error) {
            _nearbyInfoArray = [NSMutableArray arrayWithArray:response.mapItems];
//            for (MKMapItem *mapItem in _nearbyInfoArray) {
//                MKPointAnnotation *newPointAnnotation = [[MKPointAnnotation alloc] init];
//                newPointAnnotation.title = mapItem.name;
//                newPointAnnotation.subtitle = mapItem.phoneNumber;
//                newPointAnnotation.coordinate = mapItem.placemark.coordinate;
//                [_mapView addAnnotation:newPointAnnotation];
//                NSLog(@"%@,%f,%f",mapItem.name,newPointAnnotation.coordinate.longitude,newPointAnnotation.coordinate.latitude);
//            }
            [self.tableView reloadData];
        } else {
            NSLog(@"%@",error);
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _nearbyInfoArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"nearInfoCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    MKMapItem *mapItem = _nearbyInfoArray[indexPath.row];
    cell.textLabel.text = mapItem.name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MapViewController *mapVC = [[MapViewController alloc] init];
    mapVC.currentCoordinate = self.currentCoordinate;
    mapVC.destinationMapItem = _nearbyInfoArray[indexPath.row];
    [self.navigationController pushViewController:mapVC animated:YES];
//    MKMapItem *mapItem = _nearbyInfoArray[indexPath.row];
//    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
//    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:mapItem.placemark.coordinate addressDictionary:nil]];
//    toLocation.name = mapItem.name;
//    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
//                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
